const http = require('http');
const querystring = require('querystring');

class HttpRequest {
    constructor() {
        // this.set(
        // });
    }
    set(settings) {
        Object.assign(this, settings);
        return this;
    }
    get(path, data) {
        let options = {
            host: this.host ? this.host : '',
            port: this.port ? this.port : '80',
            path: path + querystring.stringify(data),
            method: 'GET',
            encoding: null,
            headers: this.headers
        }
        return new Promise((resolve, reject) => {
            let body = ''
            let req = http.request(options, response => {
                response.on('data', chunk => {
                    body += chunk
                })
                response.on('end', () => {
                    resolve(body.toString())
                })
                response.on('error', err => {
                    reject(err);
                });
            })
            req.end();
        })
    }

    /*
    post(path, data) {
        var data = querystring.stringify(data);
        var options = {
            host: this.host,
            port: this.port,
            path: path,
            method: 'POST',
            headers: Object.assign({
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
                    'Content-Length': Buffer.byteLength(data), //返回字符串实际占据的字节长度
            }, this.headers)
        };
        //判断是否为https请求
        if (status) {
            http = require('https');
            options.port = 443;
        }
        return new Promise(function(resolve, reject) {
            let body = '';
            var req = http.request(options, function(response) {
                //console.log(response.statusCode);
                response.on('data', function(chunk) {
                    body += chunk;
                });

                response.on('end', () => {
                    resolve(body);
                });

                response.on('error', err => {
                    reject(err);
                });
            });

            req.write(data);
            req.end();
        });
    }
    */
}

module.exports = HttpRequest;